<template>
  <div class="app-container">
    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAdd"
              v-hasPermi="['activity:type:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['activity:type:delete']"
            >删除</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
          <el-form-item label="类型名称" prop="typeName">
            <el-input
              v-model="queryParams.typeName"
              placeholder="请输入类型名称"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </template>

      <el-table
        v-loading="loading"
        :data="typeList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="类型ID" align="center" prop="id" />
        <el-table-column label="类型名称" align="center" prop="typeName" />
        <el-table-column label="描述" align="center" prop="description" :show-overflow-tooltip="true" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button
              type="primary"
              link
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['activity:type:edit']"
            >修改</el-button>
            <el-button
              type="primary"
              link
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['activity:type:delete']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改活动类型对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="类型名称" prop="typeName">
          <el-input v-model="form.typeName" placeholder="请输入类型名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            placeholder="请输入内容"
            :rows="4"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import ActivityAPI from '@/api/activity.api';

// 遮罩层
const loading = ref(false);
// 选中数组
const ids = ref([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 活动类型表格数据
const typeList = ref([]);
// 弹出层标题
const title = ref('');
// 是否显示弹出层
const open = ref(false);

// 表单参数
const form = reactive({
  id: undefined,
  typeName: '',
  description: ''
});

// 表单校验
const rules = reactive({
  typeName: [
    { required: true, message: '类型名称不能为空', trigger: 'blur' },
    { max: 50, message: '类型名称长度不能超过50个字符', trigger: 'blur' }
  ]
});

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  typeName: undefined
});

const formRef = ref();
const queryRef = ref();

/** 查询活动类型列表 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await ActivityAPI.getActivityTypePage(queryParams);
    typeList.value = res.list;
    total.value = res.total;
    console.log('活动类型列表数据:', typeList.value);
  } catch (error) {
    console.error('获取活动类型列表失败', error);
  } finally {
    loading.value = false;
  }
};

// 格式化日期时间
const formatDateTime = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

// 取消按钮
const cancel = () => {
  open.value = false;
  resetForm();
};

// 表单重置
const resetForm = () => {
  form.id = undefined;
  form.typeName = '';
  form.description = '';
  formRef.value?.resetFields();
};

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

// 重置按钮操作
const resetQuery = () => {
  queryRef.value?.resetFields();
  queryParams.pageNum = 1;
  queryParams.typeName = undefined;
  handleQuery();
};

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

// 新增按钮操作
const handleAdd = () => {
  resetForm();
  open.value = true;
  title.value = '添加活动类型';
};

// 修改按钮操作
const handleUpdate = async (row) => {
  resetForm();
  try {
    const res = await ActivityAPI.getActivityTypeForm(row.id);
    Object.assign(form, res);
    open.value = true;
    title.value = '修改活动类型';
  } catch (error) {
    console.error('获取活动类型详情失败', error);
    ElMessage.error('获取活动类型详情失败');
  }
};

// 提交按钮
const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return;
    
    try {
      let res;
      if (form.id) {
        res = await ActivityAPI.updateActivityType(form.id, form);
      } else {
        res = await ActivityAPI.addActivityType(form);
      }
      
      ElMessage.success('保存成功');
      open.value = false;
      getList();
    } catch (error) {
      console.error('保存活动类型失败', error);
      ElMessage.error('保存失败，请稍后重试');
    }
  });
};

// 删除按钮操作
const handleDelete = (row) => {
  const selectedIds = row.id || ids.value.join(',');
  if (!selectedIds) {
    ElMessage.warning('请选择要删除的活动类型');
    return;
  }
  
  ElMessageBox.confirm('确认删除所选活动类型吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await ActivityAPI.deleteActivityType(selectedIds);
      // 直接处理响应结果
      ElMessage.success('删除成功');
      getList();
    } catch (error) {
      console.error('删除活动类型失败', error);
      ElMessage.error('删除失败，请稍后重试');
    }
  }).catch(() => {});
};

onMounted(() => {
  getList();
});
</script> 